import { Component } from 'react';

import { Boxs,Avatar,Popup,Button} from 'saltui';

const { HBox,Box } = Boxs;
const avatarColors = ['#38adff'];

const TodoList = React.createClass({
	getInitialState: function() {//组件相关的状态对象
        return {
			allPerson: this.props.allPerson,
			visible:false,
			top:'0'
        };
    },
	handleDel:function(delIndex){
		if(!this.props.readOnly){
			this.props.value.splice(delIndex,1);
			this.props.onChange(this.props.value);
		}
	},
	handleTypeDel:function(delIndex,emplId){
		if(!this.props.readOnly){
			this.props.value.splice(delIndex,1);

			var allPerson = this.props.allPerson;
			for(let j=0;j<allPerson.length;j++){//所有的用户
				if(allPerson[j].emplId == emplId){
					allPerson[j].checked=false;
				}
			}
			this.props.onTypeChange(this.props.value,allPerson);
		}
	},
	handleAdd :function() {
		// 只读                                 选人不是选择类型，单选且选择了一个后                                                    当是候选人时，选的人数大于等于候选人数                                    
	   if(this.props.readOnly || (this.props.multiple==false && this.props.value.length==1 && this.props.type != '1' )|| (this.props.type==2 &&  this.props.value.length>=this.props.allPerson.length)){
		return false;
	   }
	   //当选人是选择时,不是一个数组/如果是数组且数组为空
	   if(this.props.type == '1' && !Array.isArray(this.props.allPerson) && (Array.isArray(this.props.allPerson)&& this.props.allPerson.length==0) && this.props.multiple==false && this.props.value.length==1){
		 return false;
	   }
	  let t = this;
	  var item = this.props;
		//var Dom = ReactDOM.findDOMNode(this.refs.addnew);
		var type = item.type;//选人类型，1：代表从全部范围中选，2：代表从某些用户中写
		var corpId = item.corpId;
	  var multiple = item.multiple;
		var allPerson = item.allPerson;
	 // alert(JSON.stringify(allPerson));
			//allPerson = ["070053103921038378,064429645523409787,2027573355740534"];
		if(type == 2){

			var value = this.props.value;
			
			if(multiple){//多选
				var disabledUsers = [];
				var userids = [];
				value.map(function(item){
					if(isIos() == "android"){
						disabledUsers.push(item.emplId);
					}else{
						userids.push(item.emplId);
					}
				});
				dd.biz.customContact.multipleChoose({
					title: '选择人', //标题
					users: allPerson,//一组员工工号
					corpId: corpId,//企业 ID，
					isShowCompanyName: false,   //true|false，默认为 false
					selectedUsers: userids, //默认选中的人，注意:已选中不可以取消
					disabledUsers: disabledUsers, //不能选的人
					max: 1000, //人数限制
					onSuccess: function(data) {
						var newData = value.concat(data);
						t.changeData(newData);
					},
					onFail : function(err) {}
				});
			}else{
			dd.biz.customContact.choose({
				title: '选择人', //标题
				users: allPerson,//一组员工userid
				corpId: corpId,//加密的企业 ID，
				isShowCompanyName: true,   //true|false，默认为 false
				disabledUsers: [], //不能选的人
				onSuccess: function(data) {
					t.changeData(data);
				},
				onFail : function(err) {}
			});
			}
		}else{
			var value = this.props.value;
			var userids = [];
			value.map(function(item){
				userids.push(item.emplId);
			});
			// dd.biz.contact.complexPicker({
			// 	title:"选择人",            //标题
			// 	corpId:corpId,              //企业的corpId
			// 	multiple:multiple,            //是否多选
			// 	limitTips:"超出了",          //超过限定人数返回提示
			// 	maxUsers:1000,            //最大可选人数
			// 	pickedUsers:userids,            //已选用户
			// 	pickedDepartments:[],          //已选部门
			// 	disabledUsers:[],            //不可选用户
			// 	disabledDepartments:[],        //不可选部门
			// 	requiredUsers:[],            //必选用户（不可取消选中状态）
			// 	requiredDepartments:[],        //必选部门（不可取消选中状态）
			// 	appId:appid,              //微应用的Id
			// 	permissionType:"GLOBAL",          //选人权限，目前只有GLOBAL这个参数
			// 	responseUserOnly:true,        //返回人，或者返回人和部门
			// 	startWithDepartmentId:0,   // 0表示从企业最上层开始
			// 	onSuccess: function(result) {
			// 		var userList = result.users;
			// 		alert(JSON.stringify(userList));
			// 		t.changeData(userList);
			// 	},
			// 	onFail : function(err) {
			// 		alert(JSON.stringify(error));
			// 	}
			// });
			dd.biz.contact.choose({
				startWithDepartmentId: 0, //-1表示打开的通讯录从自己所在部门开始展示, 0表示从企业最上层开始，(其他数字表示从该部门开始:暂时不支持)
				multiple: multiple, //是否多选： true多选 false单选； 默认true
				users: userids, //默认选中的用户列表，userid；成功回调中应包含该信息
				disabledUsers:[],// 不能选中的用户列表，员工userid
				corpId: corpId, //企业id
				max: 1000, //人数限制，当multiple为true才生效，可选范围1-1500
				limitTips:"超出了", //超过人数限制的提示语可以用这个字段自定义
				isNeedSearch:true, // 是否需要搜索功能
				title : "选择人员", // 如果你需要修改选人页面的title，可以在这里赋值 
				local:"false", // 是否显示本地联系人，默认false
				onSuccess: function(data) {
					if(type == 1 && Array.isArray(allPerson) && allPerson.length>0){//有候选人的选择
						t.changeTypeData(data);
					}else{
						t.changeData(data);
					}
					
				},
				onFail : function(err) {}
			  });
		}	
	  //var newthing = "吴小真";
	  
	},
	changeData:function(data){
	  //var rows = this.props.value;
	  // if (data !== null&& data.length>0) {
		// data.map(function(item){
		// 	item.key = item.emplId;
		// 	item.label = item.name;
		// });
		//rows.push(data);
		this.props.onChange(data);
	},
	changeTypeData:function(data){
		var value = this.props.value;//已选中的用户
		value=data;

		var allPerson = this.props.allPerson;
		for(let i=0;i<data.length;i++){
			let hasItem = false;
			for(let j=0;j<allPerson.length;j++){//所有的用户
				if(allPerson[j].emplId == data[i].emplId){
					allPerson[j].checked=true;
					hasItem = true;
				}else{
					if(i==0){
						allPerson[j].checked=false;
					}
				}
			}
			if(!hasItem){//如果原来没有这个用户则添加上去
				allPerson.push({emplId:data[i].emplId,name:data[i].name,checked:true});
			}
		}
		this.props.onTypeChange(value,allPerson);
	},
	checked:function(data){
		if(data.checked){//取消勾选
			var value = this.props.value;
			for(let i=0;i<value.length;i++){//已选中的用户
				if(value[i].emplId == data.emplId){
					value.splice(i,1);
				}
			}

			var allPerson = this.props.allPerson;
			for(let j=0;j<allPerson.length;j++){//所有的用户
				if(allPerson[j].emplId == data.emplId){
					allPerson[j].checked=false;
				}
			}
			this.props.onTypeChange(value,allPerson);
		}else{//勾选
			var value = [];
			var allPerson = [] ;
			if(this.props.multiple){//多选
				value = this.props.value;
				value.push({emplId:data.emplId,name:data.name});

				allPerson = this.props.allPerson;
				for(let j=0;j<allPerson.length;j++){//所有的用户
					if(allPerson[j].emplId == data.emplId){
						allPerson[j].checked=true;
					}
				}
			}else{//单选
				value = this.props.value;
				value.splice(0,value.length);
				value.push({emplId:data.emplId,name:data.name});

				allPerson = this.props.allPerson;
				for(let j=0;j<allPerson.length;j++){//所有的用户
					if(allPerson[j].emplId == data.emplId){
						allPerson[j].checked=true;
					}else{
						allPerson[j].checked=false;
					}
				}
			}
			this.props.onTypeChange(value,allPerson);
		}
	},
	makesure:function(){
		$("#App").removeAttr("style");
        $(document).scrollTop(this.state.top);
		this.setState({visible:false});
	},
	cancel:function(){
		//$("#App").removeAttr("style");
        //$(document).scrollTop(this.state.top);
		//this.setState({visible:false});
		var allPerson = this.props.allPerson;
		for(let j=0;j<allPerson.length;j++){//所有的用户
			if(allPerson[j].checked){
				allPerson[j].checked=false;
			}
		}
		this.props.onChange([],allPerson);
	},
	handleAddShowPopup:function(boolean){
		var top = $(window).scrollTop();

		$('#App').css("top",-top+"px");
		$('#App').css("width",100+"%");
		$('#App').css('position','fixed');
		this.setState({visible:boolean,top:top});
	},
	// render:function(){
	//   return ( 
	// 	<div className="t-group-list ">
	// 		  <HBox className="t-field-box dd-employee-todolist t-fw t-PT10 t-PB10">
	// 		  {
	// 			this.props.todo.map(function(item,i){
	// 			return (              
	// 			  <div onClick={this.handleDel.bind(this,i)}>
	// 				<Avatar size={50} name={item} colors={avatarColors} />
	// 				<p className="t-omit2 t-employee-field-list-item-name">{Avatar.formatName(item)}</p>
	// 				<i className="iconfont icon-minus t-FCc"></i>
	// 				<i className="iconfont icon-arrow-right"></i>
	// 			  </div>
	// 			)
	// 			}.bind(this))
	// 		  }
	// 		  <div onClick={this.handleAdd.bind(this)} name="新增项" ref="addnew"  className="dd-employee-add">
	// 			<i className="iconfont icon-plus"></i>
	// 		  </div>
	// 		</HBox>
		  
	// 	</div>
	//   )}
	render:function(){
		return (
				//显示的类型,0代表新增按钮在右边和label在一行
				this.props.showType=='0'?
				<div className="t-group-list ">
				<div className="t-field-box t-FBH t-FBAC t-FBJ">
				  <div className={this.props.required?"t-field-layout-h-label t-FS16 required":"t-field-layout-h-label t-FS16 "}>{this.props.label}</div>
				  <div flex={1} onClick={this.handleAdd.bind(this,this.props)}  ref="addnew"  className={this.props.readOnly?"t-DN":"t-PR dd-file-add"}>
				  	{this.props.value.length>0?'共'+this.props.value.length+'人':this.props.placeholder}&nbsp;
					 <i className="iconfont icon-plus1 t-FS20"></i> 
				  </div>
				</div>
				<HBox className={this.props.value.length>0?"t-field-box dd-employee-todolist t-fw":'t-DN'}>
				{
				  this.props.value.map(function(item,i){
				  return (              
					<div onClick={this.handleDel.bind(this,i)}>
					  <Avatar size={50} name={item.label} src={item.avatar} colors={avatarColors} />
					  <p className="t-omit2 t-employee-field-list-item-name" style={{width:54}}>{item.label}</p>
					  <i className={this.props.readOnly?'t-DN':"iconfont icon-minus t-FCc"}></i>
					</div>
				  )
				  }.bind(this))
				}
		  		</HBox>
		  </div>
		: this.props.type == '1'&&(this.props.readOnly==false) && (Array.isArray(this.props.allPerson) && this.props.allPerson.length>0)?
				<div >
				<div className="t-group-list">
						{/* <div className="t-field-layout-v-label t-FS16">会议提醒</div> */}
						<HBox className="t-field-box dd-employee-todolist t-fw t-PT10">
						{
							this.props.value.map(function(item,i){
							return (              
								<div onClick={this.handleTypeDel.bind(this,i,item.emplId)} data-key={i}>
									<Avatar size={50} name={item.name} src={item.avatar} colors={avatarColors} />
									<p className="t-omit2 t-employee-field-list-item-name" style={{width:54}}>{item.name}</p>
									<i  className={this.props.readOnly?'t-DN':"iconfont icon-minus t-FCc"}></i>
									<i className={((this.props.readOnly || (this.props.multiple==false && this.props.value.length==1)) && i==this.props.value.length-1) || this.props.participantMode == '1'?'t-DN':'iconfont icon-arrow-right'}></i>
								</div>
							)
							}.bind(this))
						}
						<div onClick={this.handleAddShowPopup.bind(this,true)} name="新增项" ref="addnew"  className={this.props.readOnly || (this.props.multiple==false && this.props.value.length==1) ?"t-DN":"dd-employee-add"}>
							<i className="iconfont icon-plus"></i>
						</div>
					</HBox>
				 </div>	
				 <div >
				 <Popup
				   content={ 
		 
					<div className="t-BCf" style={{width:300}}>
						<div className="dd-popup-container" style={{width:"100%"}}>
						<div  style={{position: 'absolute',left:0,right:0,bottom:56,top:0,overflow:'auto'}}>
							{
								this.props.allPerson.map((item,key)=>(
								<div>
									<HBox vAlign="center" className="dd-bottom-border " onClick={this.checked.bind(this,item)}>
									<Box className="t-PL16" >
										<div className={item.checked?'t-checkbox-field-icon-list':'t-checkbox-field-icon-list un-checked'} >
										<i className="iconfont icon-checked t-FCf t-FS14"></i>
										</div>
									</Box>
									<Box className="t-PT12 t-PB12 t-PL10 t-PR6"><Avatar size={40} name={item.name} src={item.avatar} colors={avatarColors} /></Box>
									<HBox flex={1} >
										<Box flex={1} className="t-FS16 t-PL4 t-PR10 t-omit t-WB">{item.name}</Box>
									</HBox>
									</HBox>
								</div>
								))
							}
							<div className="t-PL16 t-PR16 t-PT10 t-PB10">
							<div onClick={this.handleAdd.bind(this,this.props)} name="新增项" ref="addnew"  className={"dd-employee-add "}>
								<i className="iconfont icon-plus"></i>
							</div>
							</div>
						</div>
						
				
						<HBox vAlign="center" className="t-bottom-fixed t-P16 t-PT10 t-PB10">
						<Box flex={1}>
				
						</Box>
						<Box className="t-MR4">
							<Button type="secondary" size="small" display="inline" onClick={this.cancel.bind(this)}>清空</Button>
						</Box>
						<Box>
							<Button type="primary" size="small" display="inline" onClick={this.makesure.bind(this)}>确定</Button>
						</Box>
						</HBox>
					</div>
					</div>
			   	}
				   animationType="slide-left"
				   onMaskClick={() => { this.setState({ visible: false });$("#App").removeAttr("style");
				   $(document).scrollTop(this.state.top);}}
				   visible={this.state.visible}
				 >
				   {null}
				 </Popup>
			</div> 
			</div>	
		:<div className="t-group-list">
						{/* <div className="t-field-layout-v-label t-FS16">会议提醒</div> */}
						<HBox className="t-field-box dd-employee-todolist t-fw t-PT10">
						{
							this.props.value.map(function(item,i){
							return (              
								<div onClick={this.handleDel.bind(this,i)} data-key={i}>
									<Avatar size={50} name={item.name} src={item.avatar} colors={avatarColors} />
									<p className="t-omit2 t-employee-field-list-item-name" style={{width:54}}>{item.name}</p>
									<i  className={this.props.readOnly?'t-DN':"iconfont icon-minus t-FCc"}></i>
									<i className={((this.props.readOnly || (this.props.multiple==false && this.props.value.length==1) || (this.props.type==2 &&  this.props.value.length>=this.props.allPerson.length)) && i==this.props.value.length-1) || this.props.participantMode == '1'?'t-DN':'iconfont icon-arrow-right'}></i>
								</div>
							)
							}.bind(this))
						}
						<div onClick={this.handleAdd.bind(this,this.props)} name="新增项" ref="addnew"  className={this.props.readOnly || (this.props.multiple==false && this.props.value.length==1) || (this.props.type==2 &&  this.props.value.length>=this.props.allPerson.length)?"t-DN":"dd-employee-add"}>
							<i className="iconfont icon-plus"></i>
						</div>
					</HBox>
			</div>	
		)}
  });

  
export default class PageHome extends Component {
	constructor(props) {
		super(props);
		this.state = {
			refId:props.activityId
		};
	}

	componentDidMount() {
		let t = this;
	}

	clickAdd(){
		if(this.props.type == '1' && (Array.isArray(this.props.allPerson) && this.props.allPerson.length>0)){//当使用了选择时，且有候选人
			this.refs[this.props.activityId].handleAddShowPopup(true);
		}else{
			this.refs[this.props.activityId].handleAdd();
		}
	}



	getPersion(data){
		this.props.onChange(data);
	}

	onTypeChange(value,allPerson){
		this.props.onTypeChange(value,allPerson);
	}

	render() {
		const t = this;
		return (
			<div >
				{/* {
					this.props.type == 2 ? */}
					<TodoList  
						onChange={this.getPersion.bind(this)}
						onTypeChange={this.onTypeChange.bind(this)}
						value={this.props.value} 
						required={this.props.required}
						readOnly={this.props.readOnly}
						tip={this.props.tip}
						label={this.props.label}
						placeholder={this.props.placeholder}
						multiple={this.props.multiple}
						corpId={this.props.corpId}
						allPerson={this.props.allPerson}
						showType={this.props.showType}
						type = {this.props.type}
						participantMode={this.props.participantMode}
						taskId={this.props.activityId}
						ref={this.state.refId}
					/>	
					{/* :
					<EmployeeField
						required={this.props.required}
						readOnly={this.props.readOnly}
						tip={this.props.tip}
						label={this.props.label}
						placeholder={this.props.placeholder}
						multiple={this.props.multiple}
						corpId={this.props.corpId}
						value={this.props.value}
						onChange={this.getPersion.bind(this)}
						startWithDepartmentId={this.props.startWithDepartmentId}
					/>
				} */}
			</div>
		)
	}
}
